import {
    Injectable,
    Req,
    HttpException,
    HttpStatus,
    UseGuards,
    Logger,
    UploadedFiles,
    Post,
    UseInterceptors
} from '@nestjs/common';
import {UserListResult,UserListQuery} from "./user.dto"
import {CodeErrorModule} from "../../common/middleware/error/error.code"
import {User} from "../../entity/mongo/user.entity";
import {InjectRepository,InjectConnection,InjectEntityManager} from '@nestjs/typeorm'
import {Connection, EntityManager, ObjectID, Repository} from "typeorm";
import {Photo} from "../../entity/mongo/photo.entity";
import {Cron} from '@nestjs/schedule';
import {AnyFilesInterceptor} from "@nestjs/platform-express";

@Injectable()
export class UserService {
    private users: User[];
    constructor(
        @InjectRepository(User,'ucConnection')
        private readonly userRepository: Repository<User>,
        @InjectRepository(Photo,'testConnection')
        private readonly photoRepository: Repository<Photo>
    ) {
        this.users = [
            // {
            //     id:1,
            //     username: 'john',
            //     password: 'changeme',
            // },
            // {
            //     id:2,
            //     username: 'chris',
            //     password: 'secret',
            // },
            // {
            //     id:3,
            //     username: 'maria',
            //     password: 'guess',
            // },
        ];
    }

    /**
     * 测试保存
     * @param param
     */
    async save(param): Promise<User>{
        let user = new User(
            {
                username : param.username,
                password : param.password
            }
        );
        await this.userRepository.save(user);
        let photo = new Photo();
        photo.userId = user._id;
        console.log(user,photo);

        return user;

    }
    findAll(): Promise<User[]> {
        return this.userRepository.createQueryBuilder("user.tsx") // 别名，必填项，用来指定本次查询
            .innerJoinAndSelect("photo.metadata", "metadata")
            .leftJoinAndSelect("photo.albums", "albums")
            .where("photo.isPublished=true")
            .andWhere("(photo.name=:photoName OR photo.name=:bearName)")
            .orderBy("photo.id", "DESC")
            .skip(5)
            .take(10)
            .setParameters({ photoName: "My", bearName: "Mishka" })
            .getMany();
    }

    async findById(id: string): Promise<User> {
        return this.userRepository.findOne(id);
    }
    async findOne(username: string): Promise<User | undefined> {
        return this.users.find(user => user.username === username);
    }
    async remove(id: string): Promise<void> {
        await this.userRepository.delete(id);
    }
    // 返回Promise,返回list,过滤password参数
    async GetStatList(data: UserListQuery, @Req() req) : Promise<UserListResult> {
        //{
        // 	"search":"<script>alert(1)</script>",
        // 	"id":3
        // }
        return Promise.resolve({
            list: [
                new User({
                    _id: data.id || 1,
                    username: data.search || "test",
                    password: "test"
                })
            ],
            total:1
        })
    }
    // 抛出异常
    async GetError(){
       throw new CodeErrorModule(10001)
    }
    // 处理xss
    xss(query){
        function htmlEscape(text) {
            return text.replace(/&/g, '&amp;').
            replace(/</g, '&lt;').  // it's not neccessary to escape >
            replace(/"/g, '&quot;').
            replace(/'/g, '&#039;');
        }
        return htmlEscape(query.xss);
    }
    // 定时任务
    /**
     * * * * * * *
     | | | | | |
     | | | | | day of week
     | | | | month
     | | | day of month
     | | hour
     | minute
     */
    @Cron("45 * * * * *")
    handCron(){
        Logger.debug("task called when the current second is 45");
    }
    // 上传任意文件
    @Post('upload')
    @UseInterceptors(AnyFilesInterceptor())
    uploadFile(@UploadedFiles() files) {
        console.log(files);
    }

}
